package com.ewhale.feitengguest.ui.shop.mine

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.ewhale.feitengguest.R
import com.ewhale.feitengguest.dto.LoginInfoDto
import com.ewhale.feitengguest.dto.ShopAuthDto
import com.ewhale.feitengguest.presenter.shop.mine.SMinePresenter
import com.ewhale.feitengguest.ui.user.mine.ResetPhoneFirstActivity
import com.ewhale.feitengguest.utils.PictureUtils
import com.ewhale.feitengguest.utils.QiniuUtils
import com.ewhale.feitengguest.view.shop.mine.SMineView
import com.ewhale.feitengguest.widget.InputNameDialog
import com.luck.picture.lib.PictureSelector
import com.orhanobut.hawk.Hawk
import com.simga.library.activity.MBaseActivity
import com.simga.library.utils.HawkKey
import com.simga.library.utils.glide.GlideUtil
import com.simga.library.widget.SelectPhotoDialog
import kotlinx.android.synthetic.main.activity_shop_userinfo.*
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import java.util.ArrayList

class ShopUserInfoActivity : MBaseActivity<SMinePresenter>(), SMineView, EasyPermissions.PermissionCallbacks  {
    override fun showAuthInfo(shopAuth: ShopAuthDto?) {
        
    }

    override fun getViewId(): Int {
        return R.layout.activity_shop_userinfo
    }

    override fun isUseBaseTitleBar(): Boolean {
        return true
    }

    private var chooseType = 1
    private var mInfoDto: LoginInfoDto? = null
    private val mInputNameDialog by lazy(LazyThreadSafetyMode.NONE) { InputNameDialog(mContext, "请输入昵称") }
    private val mPhotoDialog by lazy(LazyThreadSafetyMode.NONE) { SelectPhotoDialog(mContext) }

    override fun init(savedInstanceState: Bundle?) {
        setTitle("我的资料")
        mInfoDto = Hawk.get<LoginInfoDto>(HawkKey.SHOP_LOGIN_INFO, null)
        if (mInfoDto != null) {
            GlideUtil.loadPicture(mInfoDto!!.headPhoto, iv_avatar, R.drawable.default_image)
            tv_phone.text = mInfoDto!!.phone
            tv_nickname.text = mInfoDto!!.nickName
        }
    }

    override fun initListener() {
        super.initListener()
        rl_avatar.setOnClickListener {
            mPhotoDialog.setOnClickItem(object : SelectPhotoDialog.onClickItem {
                override fun onOneClick() {
                    chooseType = 1
                    requestPermissionsMain()
                }

                override fun onTwoClick() {
                    chooseType = 2
                    requestPermissionsMain()
                }
            })
            mPhotoDialog.show()
        }
        rl_nickname.setOnClickListener {
            mInputNameDialog.setCommitCallBack { name -> presenter.resetNickName(name) }
            mInputNameDialog.show()
        }
        rl_phone.setOnClickListener {
            ResetPhoneFirstActivity.open(mContext, ResetPhoneFirstActivity.RESET_PHONE)
        }
        tv_reset_pwd.setOnClickListener {
            ResetPhoneFirstActivity.open(mContext, ResetPhoneFirstActivity.RESET_PASSWORD)
        }
    }
    override fun resetAvatar(imageUrl: String?) {
        if (mInfoDto != null) {
            mInfoDto!!.headPhoto = imageUrl
            GlideUtil.loadPicture(mInfoDto!!.headPhoto, iv_avatar, R.drawable.default_image)
            Hawk.put<String>(HawkKey.SHOP_AVATAR, imageUrl)
            Hawk.put<LoginInfoDto>(HawkKey.SHOP_LOGIN_INFO, mInfoDto)
        }
    }
    override fun resetName(nickname: String?) {
        if (mInfoDto != null) {
            mInfoDto!!.nickName = nickname
            tv_nickname.text = nickname
            Hawk.put<String>(HawkKey.SHOP_NICK_NAME, nickname)
            Hawk.put<LoginInfoDto>(HawkKey.SHOP_LOGIN_INFO, mInfoDto)
        }
    }

    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_2)
    private fun requestPermissionsMain() {
        val perms = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
        if (EasyPermissions.hasPermissions(mContext, *perms)) {
            if (chooseType == 1) {
                PictureUtils.openCameraRectangle(this, REQUEST_CODE_CHOOSE_COMMENT_IMAGE)
            } else {
                PictureUtils.openAluamOneRectangle(this, REQUEST_CODE_CHOOSE_COMMENT_IMAGE)
            }
        } else {
            EasyPermissions.requestPermissions(this, "申请获取相关权限",
                    REQUEST_CODE_PERMISSION_2, *perms)
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        if (chooseType == 1) {
            PictureUtils.openCameraRectangle(this, REQUEST_CODE_CHOOSE_COMMENT_IMAGE)
        } else {
            PictureUtils.openAluamOneRectangle(this, REQUEST_CODE_CHOOSE_COMMENT_IMAGE)
        }
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            AppSettingsDialog.Builder(this).setTitle("权限申请")
                    .setRationale("申请获取相关权限")
                    .setPositiveButton(getString(R.string.comfir))
                    .setNegativeButton(getString(R.string.cancle))
                    .build()
                    .show()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        if (requestCode == REQUEST_CODE_CHOOSE_COMMENT_IMAGE) {
            val images = ArrayList<String>()
            images.add(PictureSelector.obtainMultipleResult(data)[0].cutPath)
            QiniuUtils.uploadImage(images) { keys ->
                presenter.resetHeadPhoto(keys[0])
                PictureUtils.clearCache(mContext)
            }
        }
    }

    override fun showProLoading() {
        showLoading()
    }

    override fun dimissProLoading() {
        dismissLoading()
    }

    override fun showErrorMessage(postCode: Int, code: String?, message: String?) {
        showErrorMsg(code, message)
    }

    companion object {
        const val REQUEST_CODE_PERMISSION_2 = 10002
        const val REQUEST_CODE_CHOOSE_COMMENT_IMAGE = 1000

        fun open(mContext: MBaseActivity<*>) {
            mContext.startActivity(null, ShopUserInfoActivity::class.java)
        }
    }
}
